package com.wc.codeforces.思维.Collatz_Conjecture;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/6/25 22:48
 * @description https://codeforces.com/contest/1982/problem/B
 */
public class Main {
    /**
     * 思路：
     * x < y是最简单的， 因为达到一个y, 就有一个x变成1,
     * 那如果是x > y呢, 那就看下一个x是y的个数是在哪里,也就是re = y - x % y
     * 如果 k < re, 那说明达到不了下一个y的整数了, 这就简单了
     * 如果可以, 就先到达这个整数,剩下的再说
     */
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int x, y, k;

    public static void main(String[] args) {
        int T = sc.nextInt();
        while (T-- > 0) {
            x = sc.nextInt();
            y = sc.nextInt();
            k = sc.nextInt();
            // 剩下多少到达y
            while (x >= y && k > 0) {
                int re = y - x % y;
                if (re > k) break;
                k -= re;
                x = x + re;
                while (x % y == 0) x /= y;
            }
            int re = y - x % y;
            if (re <= k){
                x = 1;
                k -= re;
                k = k % (y - 1);
            }
            out.println(x + k);
        }
        out.flush();
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
